/**
 * CalcAicCompExtTest.java
 *
 * Copyright (c) 2009 Teamnet International All Rights Reserved.
 *
 * This source file may not be copied, modified or redistributed,
 * in whole or in part, in any form or for any reason, without the express
 * written consent of Teamnet International .
 **/
package ro.prjmanager.core.list;

import ro.prjmanager.core.annotations.Column;
import ro.prjmanager.core.annotations.EditOptions;
import ro.prjmanager.core.annotations.List;
import ro.prjmanager.core.annotations.SelectOption;

public class ListModel {
    StringBuilder head = new StringBuilder();
    String classParam;
   

    public ListModel(String classParam) {
        this.classParam = classParam;
    }

    public static final String STATIC_HEAD = "<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"%context_path%/jgrid/themes/sunny/jquery-ui-1.7.2.custom.css\" />\n" +
            "\t<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"%context_path%/jgrid/themes/ui.jqgrid.css\" />\n" +
            "\n" +
            "\t\n" +

            "\t<script src=\"%context_path%/jgrid/js/jquery-ui-1.7.2.custom.min.js\" type=\"text/javascript\"></script>\n" +
            "\t<script src=\"%context_path%/jgrid/js/jquery.layout.js\" type=\"text/javascript\"></script>\n" +
            "\t<script src=\"%context_path%/jgrid/js/src/grid.loader.js\" type=\"text/javascript\"></script>\n" +
            "\n" +
            "\t<script src=\"%context_path%/jgrid/js/i18n/grid.locale-en.js\" type=\"text/javascript\"></script>\n" +
            "\t<script src=\"%context_path%/jgrid/js/jquery.jqGrid.min.js\" type=\"text/javascript\"></script>\n" +
            "\t<script src=\"%context_path%/jgrid/js/jquery.tablednd.js\" type=\"text/javascript\"></script>\n" +
            "\t<script src=\"%context_path%/jgrid/js/jquery.contextmenu.js\" type=\"text/javascript\"></script>\n" /*+
            "\t<style>\n" +
            "html, body {\n" +
            "\tmargin: 0;\t\t\t*//* Remove body margin/padding *//*\n" +
            "\tpadding: 0;\n" +
            "\toverflow: true;\t*//* Remove scroll bars on browser window *//*\t\n" +
            "    font-size: 75%;\n" +
            "}\n" +
            "*//*Splitter style *//*\n" +
            "\n" +
            "\n" +
            "\n" +
            ".ui-datepicker {z-index:1200;}\n" +
            "\n" +
            "\n" +
            ".ui-tabs-nav li {position: relative;}\n" +
            ".ui-tabs-selected a span {padding-right: 10px;}\n" +
            ".ui-tabs-close {display: none;position: absolute;top: 3px;right: 0px;z-index: 800;width: 16px;height: 14px;font-size: 10px; font-style: normal;cursor: pointer;}\n" +
            ".ui-tabs-selected .ui-tabs-close {display: block;}\n" +
            ".ui-layout-west .ui-jqgrid tr.jqgrow td { border-bottom: 0px none;}\n" +
            ".ui-datepicker {z-index:1200;}" +
            "</style>"*/;

    StringBuilder colName = new StringBuilder("\ncolNames:[");
    private boolean hasEnteredColName = false;


    StringBuilder colModel = new StringBuilder("\ncolModel:[");
    private boolean hasEnteredColModel = false;

    StringBuilder footer = new StringBuilder();


    public void addColName(Column column) {
        hasEnteredColName = true;
        colName.append("'").append(column.caption()).append("',");
    }


    public void finishAddColName() {
        if (hasEnteredColName) {
            colName = colName.replace(colName.length() - 1, colName.length(), "");
        }
        colName.append("]");
    }

    public void addColModel(Column col, SelectOption selectOption) {
        hasEnteredColModel = true;
        colModel.append("\n{");
        colModel.append("name:'").append(col.name()).append("',");
        colModel.append("index:'").append(col.index()).append("',");
        colModel.append("width:").append(col.width()).append(",");
        colModel.append("align:'").append(col.align()).append("',");
        colModel.append("sortable:").append(col.sortable()).append(",");
        EditOptions editOptions = col.editOptions();
        if (col.editable()) {
            colModel.append("editable:true,");

            if (editOptions.edittype().length() > 0) {
                colModel.append("edittype:\"").append(editOptions.edittype()).append("\",");
            }
            colModel.append("editoptions:{");

            if (editOptions.edittype().equals("select")) {
                colModel.append("dataUrl:'").append(selectOption.serviceName().toLowerCase()).append(".sel?classModel=")
                        .append(classParam).append("&selectorName=").append(selectOption.id()).append("',");
            }

            if (editOptions.edittype().equals("file")) {

                colModel.append("dataEvents: [\n" +
                        "                      {  type: 'change',\n" +
                        "                         fn: function(e) {" +
                        "                             uploadFile(this.name);" +
                        "                         }" +
                        "                      }" +
                        "                   ],");
            }

            if (editOptions.rows() > 0 && editOptions.cols() > 0)
                colModel.append("rows:\"").append(editOptions.rows()).append("\",cols:\"").append(editOptions.cols()).append("\"");
            else if(!editOptions.edittype().equals("checkbox"))
                colModel.append("size:").append(editOptions.size());
            else colModel.append("size:").append("1");
            if (editOptions.initValue().length() > 0) {
                colModel.append(",dataInit:").append(editOptions.initValue());
            }

            if(editOptions.value()!=null&&editOptions.value().length()>0&&editOptions.edittype().equals("checkbox")){
                colModel.append(",value:\"").append(editOptions.value()).append("\"");
            }
            if (editOptions.defaultValue().length() > 0) {
                colModel.append(",defaultValue:\"").append(editOptions.defaultValue()).append("\"");
            }
            colModel.append("},");
            colModel.append("formoptions:{");
            colModel.append("rowpos:").append(editOptions.pos()).append(",label:\"").append(col.caption()).append("\"").append(",elmprefix:\"").append(editOptions.prefix()).append("\"");
            if (editOptions.suffix().length() > 0) {
                colModel.append(",elmsuffix:\"").append(editOptions.suffix()).append("\"");
            }
            colModel.append("}");
            if (editOptions.required()) {
                colModel.append(",editrules:{");
                colModel.append("required:true");
                colModel.append("}");
            }


        } else {
            colModel.append("editable:false,");
            colModel.append("editoptions:{");

            colModel.append("readonly:true,size:").append(editOptions.size());


            colModel.append("}");
        }

        colModel.append("},");

    }

    public void finishAddColModel() {
        if (hasEnteredColModel)
            colModel = colModel.replace(colModel.length() - 1, colModel.length(), "");
        colModel.append("\n]");
    }

    public void addFooter(List list,String methodForFilter,String filterPair,Boolean loadAfterFilter) {

        String footerStr = ("rowNum:#rowNum, rowList:[10,20,30], imgpath: gridimgpath, pager: '#pagernav#htmlIdList', sortname: '#sortName#', viewrecords: true, sortorder: \"desc\", caption:\"#title\", editurl:\"#editUrl\", height:#height}).navGrid('#pagernav#htmlIdList', {view:true}, \n" +
                "        //options \n" +
                "        {savekey: [true,13], navkeys: [true,38,40],reloadAfterSubmit:true,jqModal:false, closeOnEscape:true, bottominfo:\"#bottomInfo\",closeAfterEdit:#closeAfterEdit},\n" +
                "        // edit options \n" +
                "        {savekey: [true,13], navkeys: [true,38,40], reloadAfterSubmit:true,jqModal:false, closeOnEscape:true,bottominfo:\"#bottomInfo\",closeAfterAdd:#closeAfterAdd},\n" +
                "        // add options \n" +
                "        {reloadAfterSubmit:true,jqModal:false, closeOnEscape:true}, // del options \n" +
                "         {closeOnEscape:true}, // search options \n" +
                "         {navkeys: [true,38,40],height:#height,jqModal:false,closeOnEscape:true} // view options \n" +

                "         ); ");
        footerStr += ("");
        footerStr += ("}" +
                "); function navgrid#htmlIdList(){ return '#url?classModel=#classModel';" +
                "} ") ;

          footerStr +="</script>\n";


        footerStr += ("<table id=\"navgrid#htmlIdList\" class=\"scroll\" cellpadding=\"0\" cellspacing=\"0\"></table>\n");
        footerStr += ("<div id=\"pagernav#htmlIdList\" class=\"scroll\" style=\"text-align:center;\"></div>");
        footerStr = footerStr.replaceAll("#rowNum", String.valueOf(list.rowNum()));
        footerStr = footerStr.replaceAll("#htmlIdList", list.id());
        footerStr = footerStr.replaceAll("#bottomInfo", list.bottominfo());
        footerStr = footerStr.replaceAll("#title", list.caption());
        footerStr = footerStr.replaceAll("#editUrl", list.editUrl());
        footerStr = footerStr.replaceAll("#height", String.valueOf(list.height()));
        footerStr = footerStr.replaceAll("#closeAfterEdit", String.valueOf(list.closeAfterEdit()));
        footerStr = footerStr.replaceAll("#closeAfterAdd", String.valueOf(list.closeAfterAdd()));
        footerStr=footerStr.replaceAll("#url", list.url()).replaceAll("#htmlIdList", list.id()).replaceAll("#classModel", classParam);

        footer = new StringBuilder(footerStr);
    }

    public void addHead(List list,String methodForFilter,String filterPair,Boolean loadAfterFilter) {
         String filterStr="";
        if(methodForFilter!=null&&methodForFilter.length()>0&&filterPair!=null&&filterPair.length()>0){
            filterStr="&"+filterPair+"&meth="+methodForFilter;
        }

        head = new StringBuilder(" <script type=\"text/javascript\">\n" + "\n" + "\tvar gridimgpath='themes/sunny/images';\n"
                + "\tvar fmtDate='yy-mm-dd';\n" +
                "\tjQuery(document).ready(function() {\n");
        head.append("\tjQuery(\"#navgrid#htmlIdList\").jqGrid({ url:'#url?classModel=#classModel#meth', datatype: \"#dataType\","
                .replaceFirst("#url", loadAfterFilter!=null&&loadAfterFilter?"":list.url()).
                        replaceFirst("#htmlIdList", list.id()).
                        replaceFirst("#dataType", list.dataType()).
                        replaceFirst("#classModel", classParam).
                replaceFirst("#meth",filterStr));


    }




    @Override
    public String toString() {

        return STATIC_HEAD + "\n" + head + colName + "," + colModel + "," + footer;
    }

    public void updateFooter(String replacer, String text) {
        footer = footer.replace(footer.indexOf(replacer), footer.indexOf(replacer) + replacer.length(), text);
    }
}
